﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using YamlDotNet.RepresentationModel;

namespace FileMonSync
{
    static class Program
    {

        public const string REPO_PREFIX = "repo";

        public static List<AppHandler> handlerList = new List<AppHandler>();

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            string configPath = Path.Combine(REPO_PREFIX, "config.yaml");

            FileInfo fi = new FileInfo(configPath);
            if (!fi.Exists)
            {
                fi.Directory.Create();
                var writer = fi.CreateText();
                writer.WriteLine("apps: ");
                writer.Close();
            }

            var input = new StreamReader(configPath);
            //var input = new StreamReader(File.OpenRead("config.yaml"));

            // Load the stream
            var yaml = new YamlStream();
            yaml.Load(input);
            input.Close();

            var docs = yaml.Documents;
            if(docs.Count > 0)
            {
                var mappings =
                    (YamlMappingNode)docs[0].RootNode;
                try
                {
                    var apps = (YamlMappingNode)mappings.Children[new YamlScalarNode("apps")];
                    foreach (var app in apps)
                    {
                        string key = ((YamlScalarNode)app.Key).Value;
                        var appInfo = (YamlMappingNode)app.Value;
                        string appDir = ((YamlScalarNode)appInfo.Children[new YamlScalarNode("dir")]).Value;
                        var files = (YamlSequenceNode)appInfo.Children[new YamlScalarNode("files")];
                        string[] filesArr = new string[files.Children.Count];
                        int i = 0;
                        foreach (string file in files)
                        {
                            if(file.StartsWith(@"\") || file.StartsWith("/"))
                            {
                                filesArr[i++] = file.Substring(1);
                            }else
                            {
                                filesArr[i++] = file;
                            }
                        }
                        AppHandler handler = new AppHandler(key, appDir,filesArr);
                        handlerList.Add(handler);
                    }
                }
                catch
                {

                }
            }

            EventBus.addTrayMenuEventListener(new TrayMenuEventHandler(trayMenuClickHandler));

            Application.Run(new MainForm());
        }

        static void trayMenuClickHandler(Object sender,TrayMenuEventArgs e)
        {
            Console.WriteLine(e.Type);
        }

    }
}
